﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
using System.Collections.Generic;

/// <summary>
/// Summary description for MBFunctions
/// </summary>
public class MBFunctions
{
	public MBFunctions()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /// <summary>
    /// To send Email with neccessary fields.
    /// </summary>
    /// <param name="ToEmailID">To mail address.</param>
    /// <param name="FromMailID">From mail address.</param>
    /// <param name="subject">Subject of the mail.</param>
    /// <param name="content">Content of the mail.</param>
    /// <param name="Priority">(Integer) Priority of the mail (0 = Normal, 1 = High).</param>
    /// <param name="isHTML">(Boolean) Whether content has HTML tab.</param>
    /// <returns>True = Mail sent/ False = Mail not sent.</returns>
    public bool SentInEmailQueue(string ToEmailID, string FromMailID, string subject, string content, int Priority, bool isHTML)
    {
        bool sRet = false;
        ScreenReader SR = new ScreenReader();
        SqlConnection SqlCon = null;
        SqlCommand sqlCmd = null;
        try
        {
            string sConn = HttpContext.Current.Session["servercon"].ToString();
            HDDatabase Hdd = new HDDatabase(sConn);

            string strQuery = "INSERT INTO [email_queue] ([to_address],[from_address],[isHTML],[subject],[content],[priority],[delivery],[created_at],[row_id],[bcc_address]) " +
                "VALUES ('" + ToEmailID + "','" + FromMailID + "'," + (isHTML ? 1 : 0) + ",'" + subject + "','" + content + "'," + (Priority > 2 ? "1" : Priority.ToString()) + ",'" + DateTime.Now.ToUniversalTime() + "','" + DateTime.Now.ToUniversalTime() + "','" + SR.getHashKey() + "','')";

            SqlCon = new SqlConnection(sConn);
            sqlCmd = new SqlCommand(strQuery, SqlCon);
            int execute = Hdd.ExecuteCmdObj(sqlCmd);
            if (execute > 0) sRet = true;
            Hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SentInEmailQueue :" + ex.Message);
            return false;
        }
        finally
        {
            if (SqlCon != null)
            {
                if (SqlCon.State.Equals(ConnectionState.Open))
                    SqlCon.Close();
                SqlCon.Dispose();
            }
            if (sqlCmd != null)
                sqlCmd.Dispose();
            SR = null;
        }
        return sRet;
    }

    public bool EmailQueue(string ToEmailID, string FromMailID, string subject, string content, int Priority, bool isHTML, DateTime delivery, 
        string plainTextContent, string bcc_address, string bcc_name, string to_name, string from_name, string cc_addresss, string cc_name)
    {
        bool sRet = false;
        ScreenReader SR = new ScreenReader();
        SqlConnection SqlCon = null;
        SqlCommand sqlCmd = null;
        try
        {
            string sConn = HttpContext.Current.Session["servercon"].ToString();
            HDDatabase Hdd = new HDDatabase(sConn);

            string strQuery = "INSERT INTO [email_queue] ([to_address], [from_address], [subject], [content], [priority], [isHTML], [delivery], [plainTextContent], [bcc_address], [bcc_name], [to_name], [from_name], [cc_addresss], [cc_name], [created_at], [row_id]) " +
                "VALUES ('" + ToEmailID + "','" + FromMailID + "','" + subject + "','" + content + "'," + (Priority > 2 ? "1" : Priority.ToString()) + "," + (isHTML ? 1 : 0) + ",'" + (delivery == null ? DateTime.Now.ToUniversalTime() : delivery) + "'," +
                "'" + plainTextContent + "','" + bcc_address + "','" + bcc_name + "','" + to_name + "','" + from_name + "','" + cc_addresss + "','" + cc_name + "','" + DateTime.Now.ToUniversalTime() + "','" + SR.getHashKey() + "')";

            SqlCon = new SqlConnection(sConn);
            sqlCmd = new SqlCommand(strQuery, SqlCon);
            int execute = Hdd.ExecuteCmdObj(sqlCmd);
            if (execute > 0) sRet = true;
            Hdd = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : EmailQueue :" + ex.Message);
            return false;
        }
        finally
        {
            if (SqlCon != null)
            {
                if (SqlCon.State.Equals(ConnectionState.Open))
                    SqlCon.Close();
                SqlCon.Dispose();
            }
            if (sqlCmd != null)
                sqlCmd.Dispose();
            SR = null;
        }
        return sRet;
    }

    /// <summary>
    /// To convert the currency values available on datatable, based on user's currency value.
    /// </summary>
    /// <param name="dtSource">DataTable which has currency field.</param>
    /// <param name="sObjectId">Object id of the table.</param>
    // Implement by 'Imran gani' on 02-Feb-2014.
    public void HandleCurrencyColumn(DataTable dtSource, string sObjectId)
    {
        HDDatabase hdd = new HDDatabase();
        GenerateGrid GG = new GenerateGrid();
        Localization ll = new Localization();
        DataTable dtObjAtt = new DataTable();
        double conversionRate = 0, temp = 0, corporate = 0, inputValue = 0;
        try
        {
            GG.loadCurrencySettings();
            ArrayList currencyCode = GG.currencyCode_Rate;
            if (currencyCode.Count > 2)
            {
                corporate = double.Parse(currencyCode[2].ToString());
                conversionRate = currencyCode[0].ToString() == "" ? 1 : double.Parse(currencyCode[0].ToString());
                dtObjAtt = hdd.GetDataTable("select attrib_id from sy_obj_att where attrib_data_type = 'CU' and object_id = (select af_row_id from sy_obj where object_id = '" + sObjectId + "');");
                foreach (DataRow drAtt in dtObjAtt.Rows)
                {
                    if (dtSource.Columns.Contains(drAtt["attrib_id"].ToString()))
                    {
                        foreach (DataRow drSrc in dtSource.Rows)
                        {
                            inputValue = drSrc[drAtt["attrib_id"].ToString()].ToString() == "" ? 0 : double.Parse(drSrc[drAtt["attrib_id"].ToString()].ToString());
                            temp = (inputValue * corporate) / conversionRate;
                            drSrc[drAtt["attrib_id"].ToString()] = temp;
                            //drSrc[drAtt["attrib_id"].ToString()] = ll.getUserCurrency(temp);
                        }
                    }
                }
            }
            else
                LogWriter.WriteLog("No Corporate currency defined.");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("MBFunctions : HandleCurrencyColumn : Error : " + e.Message);
        }
        finally
        {
            hdd = null; GG = null; ll = null; dtObjAtt.Dispose();
        }
    }
}